/**
 * @Description:
 * @author 紫霞
 * @since 2019/1/17
 */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Row, Col, Card, Button, Tabs, Form, Popconfirm, Modal, message, Icon, Radio, Spin } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
//引用listPage
import ListPage from 'widget/PageTmpl/ListPage'
import cx from 'classnames'
// 当前组件样式
import styles from './productListStyle.less'
import { Grid, QueryCondition } from 'widget/Grid/index'
import { AdvanceSearch } from 'widget/CollapsiblePanels/index'
import Keypress  from 'widget/Keypress'
import { chunk } from 'lodash'
import Uploader from '../../../../widget/Upload'
import FlagBtn from 'widget/FlagBtn/FlagView'
import moment from 'moment'
const FormItem = Form.Item
const colLayout = {
  span: 24,
  offset: 0
}
let t1 = moment()

const RadioGroup = Radio.Group

const formItemLayout = {
  labelCol: {span: 9},
  wrapperCol: {span: 12}
}
const imageLayout = {
  labelCol: {span: 4},
  wrapperCol: {span: 18},
}

/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const TabPane = Tabs.TabPane
const routeView = function ({dispatch, model, form}) {
  // 表单的子函数
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  // 取出model对象，命名空间
  const {modelObj, namespace} = model
  let {loading, btnLoading, modalObj, currentItem, queryList, tableData, pageConfig, uploadFileObj, fileUrl, imageUrls} = modelObj
  // modelObj.xxx获取model中状态机的值
  console.log('modelObj', modelObj)
  // 点击处理事件
  const clickHandler = (e) => {
    // 分发到model文件中effects的xxx方法
    dispatch({
      type: `${namespace}/xxx`,
      payload: {}
    })
  }
  
  let productTypeMap = {//商品类型
    1:'房源',
    2:'停车位',
    3:'商铺',
    4:'日用快消',
    5:'家电数码',
    6:'首饰箱包',
    7:'其他'
  }
  let propertyTypeMap = {//物业类型
    11: '住宅',
    12: '公寓',
    21: '地上车位',
    22: '地下车位（非人防车位',
    23: '地下车位（人防车位）',
    24: '地下车库',
    25: '地上车库',
    31: '地上商铺',
    32: '地下商铺',
    33: '地上集中商业',
    34: '地下集中商业',
  }
  let productTypeLabelMap = {1: '详细房号', 2: '车位位置', 3: '商铺位置',4:'其他商品'}
  // 项目编号 项目名称 类型 详情  活动名称 状态 备注  创建人 创建时间
  const columns = [
    // {
    //   title: '项目编号', dataIndex: 'key', key: 'key', width: 100,
    //   render: function (value, item, index) {
    //     return index + 1
    //   }
    // },
    {title: '项目名称', dataIndex: 'name', key: 'name', width: 200,},
    {
      title: '所属城市', dataIndex: 'provinceName', key: 'provinceName', width: 150,
      render: (text, item, index) => {
        return `${item.provinceName||''}${item.provinceName&&item.cityName&&' - '||''}${item.cityName||''}`
      }
    },
    {
      title: '商品类型', dataIndex: 'productType', key: 'productType', width: 120,
      render: function (value, item, index) {
        return  productTypeMap[value]
      }
    },
    {title: '商品名称', dataIndex: 'detail', key: 'detail',width:200,},
    {title: '活动名称', dataIndex: 'activeName', key: 'activeName', },
    {
      title: '状态', dataIndex: 'status', key: 'status', width: 80,
      render: function (value, item, index) {
        return {1: '未上架', 2: '已上架', 3: '未售出', 4: '已售出', 5: '已失效'}[value]
      }
    },
    // {title: '备注', dataIndex: 'remark', key: 'remark',},
    {title: '创建人', dataIndex: 'createPerson', key: 'createPerson', width: 80,},
    {title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 180,},
    {title: '更新人', dataIndex: 'updatePerson', key: 'updatePerson', width: 80,},
    {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', width: 180,},
  ]
  // 表格模板配置
  const gridProps = {
    nameSpace: namespace,
    data: {
      columns: [].concat(columns, generateAction()),
      pageConfig, tableData
    },
    pageChange: (pageNo, pageSize) => {
      dispatch({type: `${namespace}/pageChange`, payload: {pageNo, pageSize}})
    },
    scroll: {x: 1600},
    loading
  }
  
  // 切换tab
  function onTab (key) {
    dispatch({type: `${namespace}/onTabMod`, payload: {activeKey: key}})
    dispatch({type: `${namespace}/activityList`})
  }
  
  // 表格操作区域
  function generateAction () {
    return {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 180,
      render: (data, record, index) => {
        return (
          <span>
              <FlagBtn
                  node={<a onClick={() => updateModal({item: record, index})}>详情<span className="ant-divider" /></a>}
                  btnId={'90503'}
              >
            </FlagBtn>
            {/* {console.log(!moment(record.endTime).isBefore(t1),record.status == 1,record.status ==2,record.endTime,index+1)} */}
            {record.status == 1 || record.status ==2 && !moment(record.startTime).isBefore(t1)? 
            <span>
              
              <a onClick={() => routerGo({type: 'edit', item: record})}>修改</a>{<span className="ant-divider"/>}
            </span>:null
            }
            {record.status == 5 &&
            <span>
              <a onClick={() => routerGo({type: 'edit', item: {...record, isClone: true}})}>引用</a>{<span
              className="ant-divider"/>}
            </span>
            }
            {/*{*/}
              {/*(record.status == 2) &&*/}
              {/*<Popconfirm Collapse title={`确定要${(record.activeStatus != 2) ? '下架' : '失效'}该商品吗？`} okText='确定'*/}
                          {/*cancelText='取消' onConfirm={() => {*/}
                {/*dispatch({*/}
                  {/*type: `${namespace}/relieveTimeSlot`,*/}
                  {/*payload: {id: record.seckillProductId, index}*/}
                {/*})*/}
              {/*}}>*/}
                {/*<a href='javacript:void(0)'>{(record.activeStatus != 2) ? '下架' : '失效'}</a>*/}
                {/*<span className="ant-divider"/>*/}
              {/*</Popconfirm>*/}
            {/*}*/}
              
                  
                  <FlagBtn
                  node={(record.status == 2 && record.activeStatus == 2) &&
                    <Popconfirm Collapse title={'确定要失效该商品吗？'} okText='确定'
                                cancelText='取消' onConfirm={() => {
                        dispatch({
                            type: `${namespace}/relieveTimeSlot`,
                            payload: {id: record.seckillProductId, index}
                        })
                    }}>
                        <a href='javacript:void(0)'>失效<span className="ant-divider" /></a>
                        
                    </Popconfirm>}
                  btnId={'90504'}
              >
                  </FlagBtn>
              
              {
                  (record.status == 2 && record.activeStatus != 2) &&
                  <Popconfirm Collapse title={'确定要下架该商品吗？'} okText='确定'
                              cancelText='取消' onConfirm={() => {
                      dispatch({
                          type: `${namespace}/relieveTimeSlot`,
                          payload: {id: record.seckillProductId, index}
                      })
                  }}>
                      <a href='javacript:void(0)'>下架</a>
                      <span className="ant-divider"/>
                  </Popconfirm>
              }
            {(record.status == 1) &&
            <Popconfirm Collapse title='确定要下架该商品吗？' okText='确定' cancelText='取消' onConfirm={() => {
              dispatch({
                type: `${namespace}/deleteItem`,
                payload: {id: record.seckillProductId, index}
              })
            }}>
              <a href='javacript:void(0)'>下架</a>
            </Popconfirm>
            }
          </span>
        )
      }
    }
  }
  
  // 详情页跳转
  function routerGo ({type = '', item = {}}) {
    let urlArray = MODULE_TO_ROUTES[namespace].urlArray
    hashHistory.push({
      pathname: urlArray[0],
      query: {pageType: type, id: item.seckillProductId || '', isClone: item.isClone}
    })
  }
  
  // 弹窗
  function updateModal ({item, index} = {}) {
    modalObj.visible = !modalObj.visible
    currentItem = item
    changeState({modalObj})
    if (item) {
      dispatch({
        type: `${namespace}/getDetail`,
        payload: {id: item.seckillProductId, index}
      })
    }
  }
  
  // 详情
  function handleDetailList () {
    // 项目名称 商品类型 详细房号 面积 户型 户型朝向 物业类型 竞拍标签 起拍价 原价 应付报名费 应付定金 优惠价 平方价
    let list = []
    let keys = [
      {
        name: '项目名称',
        value: currentItem['projectName'] || '',
      },
      {
        name: '商品类型',
        value: productTypeMap[currentItem['productType']],
      },
      {
        name: productTypeLabelMap[[currentItem['productType']] || ''],
        value: currentItem['detail'],
      },
      {
        name: '面积',
        value: currentItem['area'],
      },
      {
        name: '户型',
        value: currentItem['houseTypeName'],
      },
      {
        name: '户型朝向',
        value: currentItem['orientation'],
      },
      {
        name: '物业类型',
        value: propertyTypeMap[currentItem['propertyType']],
      },
      {
        name: '竞拍标签',
        value: currentItem['tags'] && currentItem['tags'].join(' ，') || '',
      },
      {
        name: '是否需要报名费',//
        value: currentItem['enrollType']&&['','否','是'][ currentItem['enrollType']],
      },
      
      {
        name: '加价幅度',
        value: currentItem['grads'],
      },
      {
        name: '是否需要报名',//
        value: currentItem['needEnroll']&&['','需要','不需要'][ currentItem['needEnroll']],
      },
      {
        name: '起拍价',
        value: currentItem['initPrice'],
      },
      {
        name: '报名费',
        value: currentItem['securityMoney']||'无',
      },
      /*      {
              name: '优惠价',//原价-起拍价
              value: currentItem['salePrice'],
            },
            {
              name: '平方价',
              value: currentItem['squarePrice'],
            },*/
      {
        name: '置业顾问姓名',//
        value: currentItem['realtyConsultant'],
      },
      {
        name: '置业顾问电话',//
        value: currentItem['consultantMobile'],
      },
      
    ]
    if(currentItem.productType == 4 || currentItem.productType == 5 ||currentItem.productType == 6 ||currentItem.productType == 7){//其他商品，不显示面积等
      keys.splice(2, 5)
      // keys.splice(keys.length-2, 2)
    }else if (currentItem.productType != 1) {//非房源类型，不显示户型和户型朝向
      keys.splice(4, 2)
    } 
    
    list = chunk(keys, 2)
    currentItem.list = list
  }
  
  handleDetailList()
  
  //修改状态
  const changeState = (payload) => {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {...payload}
    })
  }
  //修改状态
  const inputChange = (payload) => {
    let {key, value} = payload
    dispatch({
      type: `${namespace}/inputChange`,
      payload: {
        ...payload
      }
    })
  }
  //查询
  const onSearch = (payload) => {
    dispatch({
      type: `${namespace}/search`,
      payload: payload
    })
  }
  const queryReset = (payload) => {
    dispatch({
      type: `${namespace}/queryReset`,
      payload: payload
    })
  }
  
  // 批量修改最大议价---------------------开始
  
  function updateImageModel (value, fileObj) {
    console.log('updateImageModel', value, fileObj)
    imageUrls[0] = {
      url: value,
      name: fileObj.name,
    }
    // 分发到model
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {imageUrls}
    })
  }
  
  function removeImgUrl (index) {
    
    imageUrls.splice(index, 1)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {imageUrls}
    })
  }
  
  function updateUploadModal () {
    uploadFileObj.visible = !uploadFileObj.visible
    changeState({uploadFileObj})
  }
  
  // 批量修改最大议价---------------------结束
  
  function uploadConfirm () {
    uploadFileObj.visible = !uploadFileObj.visible
    changeState(uploadFileObj)
  }
  
  return (
    <div className={cx('pageLayout')}>
      {/*监控键盘事件，自动刷新数据*/}
      <Keypress keyCode={13} cbk={()=>{
        onSearch();
      }} />
      <div className="public_listMain">
        <div className="functionButton">
            <FlagBtn
                node={  <Button style={{marginRight:'15px'}} type="primary" onClick={() => routerGo({type: 'add',})}>新增商品</Button>}
                btnId={'90501'}
            >
            </FlagBtn>
            <FlagBtn
                node={ <Button type="primary" onClick={() => {updateUploadModal()}}>批量导入商品</Button>}
                btnId={'90502'}
            >
            </FlagBtn>
        </div>
        <AdvanceSearch
          footer={
            <span>
                <Button type="primary" htmlType="submit" onClick={() => onSearch()} loading={loading}>搜索</Button>
                <Button onClick={() => dispatch({type: `${namespace}/queryReset`})}>重置</Button>
              </span>
          }
        >
          <QueryCondition
            data={queryList}
            inputChange={(key, value) => dispatch({type: `${namespace}/inputChange`, payload: {key, value}})}
          />
        </AdvanceSearch>
        {/* 表格区域 */}
        <div className="boxShadow">
          {/* 搜索条件 */}
          
          {/* 添加用户 */}
          <Grid {...gridProps} />
        </div>
        <Modal
          title={'详情'}
          width='800px'
          // className="pubBiz_CommonModel"
          visible={modalObj.visible}
          onCancel={() => {updateModal()}}
          footer={null}
        >
          <div className={styles.detailContainer}>
            <table>
              <tbody className={'ant-table-tbody'}>
              {
                currentItem.list.map((item, index) => {
                  let item_0 = item[0] || {}
                  let item_1 = item[1] || {}
                  return (
                    <tr key={index}>
                      
                      <td>{item_0.name}</td>
                      <td>{item_0.value}</td>
                      <td>{item_1.name}</td>
                      <td>{item_1.value}</td>
                    </tr>
                  )
                })
              }
              </tbody>
            </table>
          </div>
        </Modal>
        
        <Modal title={'导入商品列表'}
               visible={uploadFileObj.visible}
               okText={'导入'}
               cancelText={'取消'}
               confirmLoading={uploadFileObj.confirmLoading}
               onCancel={(e) => {
                 updateUploadModal()
               }}
               onOk={(e) => {
                 dispatch({
                   type: `${namespace}/importFile`,
                   payload: {}
                 })
               }}
               width='800px'>
          <div className={styles.modalCss}>
            <Form>
              <Row>
                <Col span={24}>
                  <FormItem{...imageLayout} label={'文件'}>
                    <Uploader uploadedUrls={imageUrls}
                              removeFileCbf={(index) => { removeImgUrl(index) }}
                              uploadSuccessCbf={(imgUrl, fileObj) => { updateImageModel(imgUrl, fileObj) }}
                              showType='5'
                              accept={'.xlsx,.xls'}
                              uploadTip='支持*.xlsx, *.xls格式文件。'
                              fileType='file'
                              fileMaxSize='2'
                              maxFiles='10'/>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={24}>
                  <FormItem{...imageLayout} label={'商品类型'}>
                    <RadioGroup onChange={(e) => {
                      uploadFileObj.productType = e.target.value
                      changeState({uploadFileObj})
                    }} value={uploadFileObj.productType}>
                      <Radio value={1}>房源</Radio>
                      <Radio value={2}>车位</Radio>
                      <Radio value={3}>商铺</Radio>
                      <Radio value={4}>日用快消</Radio>
                      <Radio value={5}>家电数码</Radio>
                      <Radio value={6}>首饰箱包</Radio>
                      <Radio value={7}>其他</Radio>
                    </RadioGroup>
                    <a href="javascript:void(0)" style={{'color': '#0877FD'}}
                       onClick={() => {
                         dispatch({
                           type: `${namespace}/downloadTemplate`,
                           payload: {}
                         })
                       }}>模板下载{uploadFileObj.productType && ('（' + productTypeMap[uploadFileObj.productType] + '）') || ''}</a>
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </div>
        </Modal>
      </div>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))
